package com.example.demo.zaqizabatest.调用其它服务接口;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @ClassName RestTemplate
 * @Author lys4134
 * @Date 2021/08/13 15:38:14
 * @Description RestTemplate
 * @Version 1.0
 **/
public class RestTemplateTest {

    /**
     * 日志记录
     */
    private static final Logger logger = LoggerFactory.getLogger(RestTemplateTest.class);

    /**
     * rest服务
     */
    @Autowired
    protected RestTemplate restTemplate;

    private <T>ResponseEntity<T> exchange(Map<String,String> headers, String body, HttpMethod method, String url, ParameterizedTypeReference<T> paramType){
        HttpHeaders httpHeaders = new HttpHeaders();
        if (!CollectionUtils.isEmpty(headers)){
            for (String key : headers.keySet()){
                httpHeaders.add(key, headers.get(key));
            }
        }
        HttpEntity entity;
        if (StringUtils.isEmpty(body)) {
            entity =  new HttpEntity<>(httpHeaders);
        } else  {
            entity =  new HttpEntity<>(body, httpHeaders);
        }
        logger.info("url : " + url);
        logger.info("body : " + body);
        ResponseEntity<T> result;
        try {
            result = restTemplate.exchange(url, method, entity, paramType);
            logger.info(result.getStatusCode().value() + "");
            logger.info(result.getBody().toString());
            return result;

        }catch (Exception e) {
            logger.info("接口调用失败，请联系管理员;详细信息：" + e.getMessage());
//            response.setMsg(e.getMessage());
            if (e instanceof HttpClientErrorException) {
                HttpClientErrorException h = (HttpClientErrorException) e;
                logger.info(h.getStatusCode().value() + "");
//                response.setCode(h.getStatusCode().value());
            }
        }
        return null;

    }
}
